#pragma once
#include<iostream>
#include<assert.h>
using namespace std;
namespace sty
{
	class string
	{
	public:
		typedef char* iterator;
		typedef const char* const_iterator;

		//string()
		//	:_str(new char[1] {'\0'})
		//	, _size(0)
		//	,_capacity(0)
		//{}
		string(const char* str = "")
		{
			_size = strlen(str);
			_capacity = _size;
			_str = new char[_capacity + 1];
			strcpy(_str, str);
		}
		~string()
		{
			delete[] _str;
			_str = nullptr;
			_size = _capacity = 0;
		}
		const char* c_str()
		{
			return _str;
		}
		size_t size() const
		{
			return _size;
		}
		size_t capacity() const
		{
			return _capacity;
		}

		char& operator[](size_t pos)
		{
			assert(pos < _size);
			return _str[pos];
		}
		const char& operator[](size_t pos) const
		{
			assert(pos < _size);
			return _str[pos];
		}
		iterator begin()
		{
			return _str;
		}
		iterator end()
		{
			return _str + _size;
		}
		const_iterator begin() const
		{
			return _str;
		}
		const_iterator end() const
		{
			return _str + _size;
		}
		void reserve(size_t n)
		{
			if (_capacity < n)
			{
				char* tmp = new char[n+1];
				strcpy(tmp, _str);
				delete[] _str;
				_str = tmp;
				_capacity = n;
			}
		}
		void push_back(char ch)
		{
			if (_size == _capacity)
			{
				reserve(_capacity == 0 ? 4 : _capacity * 2);
			}
			_str[_size] = ch;
			++_size;
			_str[_size] = '\0';
		}
		void append(const char* str)
		{
			size_t len = strlen(str);
			if (len + _size > _capacity)
			{
				reserve(len + _size > _capacity * 2 ? len + _size : _capacity * 2);
			}
			strcat(_str+_size, str);
			_size += len;
		}
		string& operator+=(char ch)
		{
			push_back(ch);
			return *this;
		}
		string& operator+=(const char* str)
		{
			append(str);
			return *this;
		}
		void insert(size_t pos, char ch)
		{
			assert(pos <= _size);
			if (_size == _capacity)
			{
				reserve(_capacity == 0 ? 4 : _capacity * 2);
			}
			int end = _size;
			while ((int)npos <= end)
			{
				_str[end+1] = _str[end];
				end--; 
			}
			_str[pos] = ch;
			++_size;
			
		}
		void insert(size_t pos, const char* str);
		void earse(size_t pos, size_t len = npos);

	private:

		char* _str;
		size_t _size;
		size_t _capacity;

		static const size_t npos;
	};


}
